import { _decorator, Component, Tween, tween, v2, v3, Vec3 } from 'cc';
import { EventManager, MyEvent } from './EventManager';
const { ccclass, property } = _decorator;

@ccclass('Rotate')
export class Rotate extends Component {

    public static Instance: Rotate = null;

    @property
    IsShowWeapon: boolean = false;

    startEulerAngle: Vec3 = Vec3.ZERO;
    rotationSpeed = 10;
    isClick: boolean = false;
    angle: number = 0.04;

    protected onLoad(): void {
        Rotate.Instance = this;
        this.startEulerAngle = this.node.eulerAngles.clone();
    }

    protected update(dt: number): void {
        if (this.IsShowWeapon) {
            this.node.eulerAngles = this.node.eulerAngles.add(v3(0, 0.5, 0));
            return;
        }
        if (this.isClick) return;
        if (this.node.eulerAngles.y > -74 || this.node.eulerAngles.y < -106) {
            this.node.eulerAngles = this.startEulerAngle;
        }
        if (this.node.eulerAngles.y >= -75) {
            this.angle = -this.angle;
        } else if (this.node.eulerAngles.y <= -105) {
            this.angle = -this.angle;
        }

        this.node.eulerAngles = this.node.eulerAngles.add(v3(0, this.angle, 0));
    }

    click() {
        this.unschedule(this.turnBack);
        Tween.stopAllByTarget(this.node);
        this.isClick = true;
    }

    resume() {
        this.unschedule(this.turnBack);
        this.scheduleOnce(this.turnBack, 0.5);
    }

    turnBack() {
        tween(this.node)
            .to(0.5, { eulerAngles: this.startEulerAngle })
            .call(() => {
                this.isClick = false;
            })
            .start();
    }

    rotate(rotate: Vec3) {
        // 计算旋转角度
        const rotationX = rotate.y * this.rotationSpeed * 0.1;
        const rotationY = rotate.x * this.rotationSpeed * 0.1;

        // 应用旋转
        this.node.eulerAngles = this.node.eulerAngles.add(v3(0, rotationY, 0));
    }

    protected onEnable(): void {
        EventManager.ON(MyEvent.ROTATE, this.rotate, this);
    }

}


